import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> rightSideView(TreeNode root) {

        List<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> curr = new LinkedList<>();
        curr.offer(root);
        
        // size变量
        while (!curr.isEmpty()) {
            int size = curr.size();
            while(size>0){
                TreeNode node = curr.remove();
                if (size==1) {
                    result.offer(node.val);
                }
                if (node.left != null){
                    curr.offer(node.left);
                }
                if (node.right != null){
                    curr.offer(node.right);
                }
                size--;
            }
        }


        /*双数组
        Deque<TreeNode> next = new LinkedList<>();
        while (!curr.isEmpty()) {
            while (!curr.isEmpty()) {
                if (curr.size() == 1) {
                    result.add(curr.peek().val);
                }
                TreeNode node = curr.remove();
                if (node.left != null) {
                    next.offer(node.left);
                }
                if (node.right != null) {
                    next.offer(node.right);
                }
            }
            curr = next;
            next = new LinkedList<>();
        }
         */
        return result;
    }
}